# -*- coding: utf-8 -*-
############################################################################
from datetime import datetime, timedelta
import hashlib,re,os,random
from random import choice
from storm.locals import *
from storm.expr import Sum
from accost.shortcuts import *
from accost.utils.auth import *
import simplejson as json
import logging
import urllib,string
from chee import *
############################################################################
class GlobalUtils(object):
    def getRint(self):
        return g_rint
    def encode(self,str,encoding='utf-8'):
        return urllib.quote(str.encode(encoding))
    def goodBitRate(self,brate):
        return bit_rate_to_human(brate)
    def goodFileSize(self,fsize):
        return file_size_to_human(fsize)
    def goodDuration(self,hours):
        days = hours / 24
        nhours = hours - days * 24
        rstr = u''
        if days > 0: rstr = rstr + u'%d天' % days
        rstr = rstr + u'%g小时' % nhours
        return rstr
    def getDate(self,days=0):
        return (datetime.now()+timedelta(days=days)).strftime('%Y-%m-%d')
    def nDate(self,t):
        return t.strftime('%Y-%m-%d')
    def nTime(self,t):
        return t.strftime('%Y-%m-%d %H:%M')
    def calcDate(self,end,reverse=0):
        start = datetime.now()
        days = 0
        if type(end) == type(start): days = (end - start).days
        elif type(end) == type(start.date()): days = (end - start.date()).days 
        else: days = 0
        if reverse == 1: days = abs(days)
        return days
    def minusDate(self,end):
        return minusDate(end)
    def goodTime(self,t):
        return getGoodTime(t)
    def getGenderArea(self,user,with_quote=True):
        if not user: return u''
        try:
            msg = u''
            gen = self.getGender(user.gender)
            if gen: msg = msg + gen + ' '
            if user.area_id > 0: msg = msg + user.area.name
            msg = msg.strip()
            if msg and with_quote: msg = '(%s)' % msg
            return msg
        except: return u''
    def obj2json(self,obj):
        return json.dumps(obj)
    def getGender(self,gender_int):
        if gender_int == 0: return u''
        elif gender_int == 1: return u'男 '
        else: return u'女 '
    def getGender2(self,gender_int):
        if gender_int == 0: return u'TA'
        elif gender_int == 1: return u'他'
        else: return u'她'
    def toNormalText(self,txt):
        return toText(txt)
    def getImageSize(self,path):
        return getImageSize(path)
def getUserKey(user_id,user_key):
    return hashlib.sha1('%s$%d'%(user_key,user_id)).hexdigest()
def getRandKey(length=16, chars=string.letters + string.digits):
    return unicode(''.join([choice(chars) for i in range(length)]))
def minusDate(end):
    start = datetime.now()
    if type(end) == type(start): days = (end - start).days
    elif type(end) == type(start.date()): days = (end - start.date()).days 
    else: days = 0
    if days <= 0 or days > 30: return {'type':'date','result':end.strftime('%Y-%m-%d')}
    else: return {'type':'day','result':u'%d天' % days}
def toHtml(txt):
    return txt.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;').replace('\n','</p><p>')
def toText(txt):
    return txt.replace('&amp;','&').replace('&lt;','<').replace('&gt;','>').replace('</p><p>','\n')
def getRandomName(more=False):
    dt = datetime.now()
    str_ret = dt.strftime('%y%m%d_%H%M%S')
    str_ret = u'%s%d' % (str_ret,dt.microsecond) 
    return str_ret
def sendSysMail(user_id,title,content):
    from chee.models.user import User_Mail
    mail = User_Mail()
    mail.owner_id = user_id
    mail.from_id = 0
    mail.to_id = user_id
    mail.title = title
    mail.content = content
    mail.send_time = datetime.now()
    mail.is_read = 0
    store.add(mail)
    store.commit()
def bit_rate_to_human(bit_rate):
    """返回人类易读的码流"""
    m = bit_rate / (1024. * 1024)
    if m >= 1: return u'%.1f Mbps' % m
    return u'%d Kbps' % (bit_rate/1024,)
def file_size_to_human(file_size):
    """返回人类易读的文件大小"""
    g = file_size / (1024. ** 3)
    if g >= 1: return u'%.1f G' % g
    return u'%d M' % (file_size/(1024*1024),)
def getGoodTime(t):
    retstr = ''
    if not t: return u'N/A'
    if datetime.now() < t: return u'N/A'
    delta = datetime.now() - t
    if delta.days >= 30: retstr = t.strftime('%Y-%m-%d')
    elif delta.days >= 1: retstr = u'%d天前' % (delta.days)
    elif delta.seconds < 60: retstr = u'%d秒前' % delta.seconds
    elif delta.seconds < 3600: retstr = u'%d分钟前' % (delta.seconds / 60)
    elif delta.seconds < 86400: retstr = u'%d小时前' % (delta.seconds / 3600)
    else: retstr = u'%d小时前' % (delta.seconds / 3600)
    return retstr
def constellation(dt):
    # 星座时间点12.22-1.19/1.20-2.18/2.19-3.20/3.21-4.19/4.20-5.20
    # /5.21-6.21/6.22-7.22/7.23-8.22/8.23-9.22/9.23-10.23/10.24-11.21/11.22-12.21
    splitday = [19,18,20,19,20,21,22,22,22,23,21,21]
    constell = [u'魔羯座',u'水瓶座',u'双鱼座',u'牡羊座',u'金牛座',u'双子座',
                u'巨蟹座',u'狮子座',u'处女座',u'天秤座',u'天蝎座',u'射手座']
    month = dt.month; day = dt.day; dd = 0
    if day<=splitday[month-1]: dd = 0
    else: dd = 1
    tmp = month + dd
    if tmp ==13: tmp = 1
    return constell[tmp-1]
def sendGtalkMsg(message):
    from chee.models.other import Short_Msg
    msg = Short_Msg(); msg.msg = message; store.add(msg); store.commit()
def AjaxInfo(message):
    return Response(encodeJsonMsg(False,message))
def ImageUpInfo(request,message,uploadImg = u''):
    action = request.args.get('action','').strip()
    initImg = request.args.get('initImg','').strip()
    import base64
    message = encodeUrl(message)
    query = u'action=%s&initImg=%s&err=%s' % (action,initImg,message)
    if uploadImg: query += u'&uploadImg=%s' % base64.b64encode(uploadImg) 
    return redirect('/simgup/?' + query)
def ShowInfo(req,err,message):
    tmpl = env.get_template('info.html')
    return Response(tmpl.render( request = req, errors = err, info = message ))
def IframeInfo(req,err,message):
    tmpl = env.get_template('pagelet/common/info_iframe.html')
    return Response(tmpl.render( request = req, errors = err, info = message ))
def PageletInfo(req,err,message):
    tmpl = env.get_template('pagelet/common/info_pagelet.html')
    return Response(tmpl.render( request = req, errors = err, info = message ))
def MailInfo(req,err,message):
    tmpl = env.get_template('user/mail/info.html')
    return Response(tmpl.render( request = req, errors = err, main_active = u"myspace", info = message ))
def AdminInfo(req,err,message):
    tmpl = env.get_template('admin/info.html')
    return Response(tmpl.render( request = req, errors = err, info = message ))
def encodeUrl(s,safe_char=u'/'):
    try: return urllib.quote(s,safe_char)
    except: return urllib.quote(s.encode('utf-8'),safe_char)
def decodeJsonMsg(s,obj_hook=None):
    obj = json.loads(s,encoding='utf-8', object_hook=obj_hook)
    return obj
def encodeJsonMsg(result,msg):
    resu = 'false'
    if result: resu = 'true'
    s = json.dumps({"result":resu,"message":msg})
    return s
def encodeJsonMsgPlus(result,msg,plus):
    resu = 'false'
    if result: resu = 'true'
    s = json.dumps({"result":resu,"message":msg,"plus":plus})
    return s
def showSql():
    import sys
    from storm import tracer
    from storm.tracer import DebugTracer
    tracer.remove_all_tracers()
    tracer.install_tracer(tracer.DebugTracer(sys.stdout))
def removeSql():
    import sys
    from storm import tracer
    from storm.tracer import DebugTracer
    tracer.remove_all_tracers()
def doLogout(request,resp):
    logout(request)
    return resp
def translatePath(path):
    if path.find('/')==0: path = path[1:]
    paths = os.path.split(path)
    return os.path.join(base_path,*paths)
def getImageSize(_path):
    path = _path
    if not os.path.exists(path):
        path = translatePath(_path)
        if not os.path.exists(path): return (0,0)
    if not os.path.isfile(path): return (0,0)
    import Image
    try:
        img = Image.open(path)
        return img.size
    except: return (0,0)
def listImages(path):
    if not os.path.exists(path): return []
    if not os.path.isdir(path): return []
    import Image
    results = []
    filenames = os.listdir(path)
    for fn in filenames:
        if not fn or os.path.isdir(os.path.join(path,fn)): continue
        fpath = os.path.join(path,fn)
        try: 
            imgfile = {}; imgfile['id'] = u'%s' % fn; imgfile['name'] = u'%s' % fn;
            imgfile['url'] = fpath.replace(base_path,'').replace('\\\\','/').replace('\\','/')
            stat = os.stat(fpath)
            imgfile['mtime'] = stat.st_mtime; imgfile['size'] = '%dK' % int(stat.st_size / 1024) 
            imgfile['file_size'] = '%dK' % int(stat.st_size / 1024) 
            img = Image.open(fpath)
            imgfile['width'] = img.size[0]; imgfile['height'] = img.size[1]
            results.append(imgfile)
        except: pass
    if len(results) > 0: results.sort(key=lambda x: x['mtime'], reverse=True)
    return results
def ip2long(ip):
    import struct, socket
    return struct.unpack('>L', socket.inet_aton(ip))[0]
def ip_in_range(ip, area):
    from chee.models.iprange import IpRange
    flag = IpRange.getIpInArea(ip, area)
    return flag
